package client;

import java.awt.*;
import java.awt.event.*;
import java.net.InetAddress;

import javax.swing.*;


import metier.modele.Constantes;
import metier.modele.Serveur;

/**
 * 
 * @author Quentin, Vincent, Charlie
 *
 */
public class Gestionnaire_Serveur implements ActionListener
{
	
	private JFrame fen;
	private JPanel portPanel, ipPanel, boutonPanel, clientPanel, freqSavePanel,jFilePanel, statusPanel;
	private JLabel portL, ipL, clientL, nbClientL, freqSaveL;
	private JTextField portTF, ipTF, clientTF, freqSaveTF;
	private JButton connecterB, deconnecterB, clientPlus, clientMoins, freqSavePlus, freqSaveMoins,buttonFile;
	
	private Serveur serveur;
	private JFileChooser fileChooser;
	private String pathDir = ".";

	public static int MAX_FREQSAVE = 99;
	public static int MIN_FREQSAVE = 1;
	
	public static int MAX_CLIENT = 99;
	public static int MIN_CLIENT = 1;
	
	public static int WIDTH = 380;
	public static int HEIGHT = 480;

	
	/**
	 * Constructeur
	 */
	public Gestionnaire_Serveur() 
	{

		fen = new JFrame(Constantes.SERVEUR_TITLE);
		fen.setSize(WIDTH, HEIGHT);
		fen.setResizable(false);
		fen.setLocationRelativeTo(null);
			
		// Gestionnaire de mise en forme.
		GridLayout gl = new GridLayout(7,1);
	
		fen.getContentPane().setLayout(gl);
		
		portPanel = new JPanel();
		ipPanel = new JPanel();
		boutonPanel = new JPanel();
		clientPanel = new JPanel();
		freqSavePanel = new JPanel();
		jFilePanel = new JPanel();
		statusPanel = new JPanel();
		fen.getContentPane().add(ipPanel);
		fen.getContentPane().add(portPanel);
		fen.getContentPane().add(clientPanel);
		fen.getContentPane().add(jFilePanel);
		fen.getContentPane().add(freqSavePanel);
		fen.getContentPane().add(statusPanel);
		
		
		// IP & Port
		
		portL = new JLabel("Port : ");
		portTF = new JTextField(""+Constantes.DEFAULT_PORT, 4);
		
		ipL = new JLabel("IP : ");
		String ip = getLocalIP();
		ipTF = new JTextField(ip, ip.length()-2);
		ipTF.setEditable(false);
				
		portPanel.add(portL);
		portPanel.add(portTF);
		
		ipPanel.add(ipL);
		ipPanel.add(ipTF);
		
		
		
		// Client Max (+ / -)
		
		clientL = new JLabel("Client Max : ");
		
		clientTF = new JTextField("10", 2);
		clientTF.setEditable(false);
		
		clientPlus = new JButton("+");
		clientPlus.addActionListener(this);
		
		clientMoins = new JButton("-");
		clientMoins.addActionListener(this);
				
		clientPanel.add(clientL);
		clientPanel.add(clientMoins);
		clientPanel.add(clientTF);
		clientPanel.add(clientPlus);
		
		// FreqSave (+ / -)
		
		freqSaveL = new JLabel("Freq. Sauv. (min) : ");
		
		freqSaveTF = new JTextField("1", 2);
		freqSaveTF.setEditable(false);
		
		freqSavePlus = new JButton("+");
		freqSavePlus.addActionListener(this);
		
		freqSaveMoins = new JButton("-");
		freqSaveMoins.addActionListener(this);
				
		freqSavePanel.add(freqSaveL);
		freqSavePanel.add(freqSaveMoins);
		freqSavePanel.add(freqSaveTF);
		freqSavePanel.add(freqSavePlus);
		
		JLabel labelFile = new JLabel("Workspace : ");
		buttonFile = new JButton("Browse");
		buttonFile.addActionListener(this);
		fileChooser = new JFileChooser();
		fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		this.jFilePanel.add(labelFile);
		this.jFilePanel.add(buttonFile);
		
		
		// Connexion / Déconnexion
		
		connecterB = new JButton("Connexion");
		connecterB.setIcon(new ImageIcon(this.getClass().getResource("/img/icon/icone_acces2.gif")));
		connecterB.addActionListener(this);
		
		deconnecterB = new JButton("Déconnexion");
		deconnecterB.setIcon(new ImageIcon(this.getClass().getResource("/img/icon/icone_popup_ko.png")));
		deconnecterB.addActionListener(this);
		deconnecterB.setEnabled(false);		
		
		boutonPanel.add(connecterB);
		boutonPanel.add(deconnecterB);
		
		fen.getContentPane().add(boutonPanel);
		
		
		
		// NB clients connectés
		
		nbClientL = new JLabel("Client connecté : 0");
		statusPanel.add(nbClientL);
		
		
		fen.setVisible(true);
		
		
		fen.addWindowListener (new WindowAdapter()
		{	public void windowClosing (WindowEvent e)
			{ 
				if (serveur != null)
					serveur.deconnexionServeur();
				System.exit(0);
			}
		});		
		
	}


	/**
	 * Met à jour le nombre de connecté
	 * @param n
	 */
	public void updateConnectes(int n)
	{
		if (n < 2)
			nbClientL.setText("Client connecté : " + n);
		else
			nbClientL.setText("Clients connectés : " + n);
	}
	
	
	/**
	 * Détecte les appuies sur les boutons
	 */
	public void actionPerformed (ActionEvent e)
	{
		Object source =	e.getSource();
				
		
		// ++ Client
		if (source == clientMoins || source == clientPlus)
		{
			int nbClient = Integer.parseInt(clientTF.getText());
			nbClient = nbClient + (source == clientMoins ? -1 : +1);
			
			if (nbClient < MIN_CLIENT)
				nbClient = MIN_CLIENT;

			if (nbClient > MAX_CLIENT)
				nbClient = MAX_CLIENT;
			
			clientTF.setText("" + nbClient);
			
		}
		
		// freqSave++
		if (source == freqSaveMoins || source == freqSavePlus)
		{
			int nbFreqSave = Integer.parseInt(freqSaveTF.getText());
			nbFreqSave = nbFreqSave + (source == freqSaveMoins ? -1 : +1);
			
			if (nbFreqSave < MIN_FREQSAVE)
				nbFreqSave = MIN_FREQSAVE;

			if (nbFreqSave > MAX_FREQSAVE)
				nbFreqSave = MAX_FREQSAVE;
			
			freqSaveTF.setText("" + nbFreqSave);
			
		}
		if(source == buttonFile) {
			if (fileChooser.showSaveDialog(null) != JFileChooser.CANCEL_OPTION){
				String path = this.fileChooser.getSelectedFile().toString();
				System.out.println(path);
				this.pathDir = path;
			}
		}
		//// Connecter le serveur
		if (source == connecterB) 
		{
			int port = Integer.parseInt(portTF.getText());
			if (port > 0 && port < 65535)
			{
				int clientMax = Integer.parseInt(clientTF.getText());
				int freqSave = Integer.parseInt(freqSaveTF.getText());
				try
				{
					serveur = new Serveur (port, clientMax, freqSave, this,pathDir);
					if (serveur.checkPIDFile() == true) // Est-ce que le serveur a crash ?
					{
						System.out.println("Il semblerait que le serveur a crashé ... Tentative de récupération du dernier fichier SVG ...");
						serveur.loadLastSVGFile();
						serveur.removePIDFile();
					}
					serveur.addPIDFile();
					connecterB.setEnabled(false);
					deconnecterB.setEnabled(true);
					clientTF.setEnabled(false);
					portTF.setEnabled(false);
					clientPlus.setEnabled(false);
					clientMoins.setEnabled(false);
					buttonFile.setEnabled(false);
					freqSavePlus.setEnabled(false);
					freqSaveMoins.setEnabled(false);
				}
				catch (Exception ex)
				{
					JOptionPane.showMessageDialog(null, Constantes.SERVEUR_PORT_IN_USE, fen.getTitle(), 0);
				}
			}
		}
		
		//// Déconnecter le serveur
		if (source == deconnecterB) {
			
			int question = JOptionPane.showConfirmDialog(null,
					Constantes.SERVEUR_DECONNEXION,
				    fen.getTitle(),
				    JOptionPane.OK_CANCEL_OPTION);
			
			if (question == JOptionPane.OK_OPTION)
			{
				serveur.deconnexionServeur();
				connecterB.setEnabled(true);
				deconnecterB.setEnabled(false);
				clientTF.setEnabled(true);
				portTF.setEnabled(true);
				clientPlus.setEnabled(true);
				clientMoins.setEnabled(true);
				buttonFile.setEnabled(true);
				freqSavePlus.setEnabled(true);
				freqSaveMoins.setEnabled(true);
				updateConnectes(0);
			}
		}
	}	
	
	/**
	 * Pour récupéré l'IP local
	 * @return IP
	 */
	private String getLocalIP()
	{
		try
		{
			InetAddress ownIP=InetAddress.getLocalHost();
			return ownIP.getHostAddress();
		}
		catch (Exception e){
			System.out.println("Exception caught ="+e.getMessage());
			return "127.0.0.1";
		}
	}
	
}